<?php
namespace Modules\Home\Controllers;

use Common\Models\UserModel;
use Modules\Home\Validations\UserValidation;

class LoginController extends ControllerBase {
  public function initialize() {
    
  }

  public function indexAction() {
    if($this -> session -> has('user')) {
      return $this -> response -> redirect('/');
    }
  }

  public function loginAction() {
    $validation = (new UserValidation()) -> login($this -> request -> getPost());
    if($validation['code'] != 0) {
      return $this -> _returnScript($validation['message'], '/login');
    }

    $user = $validation['user'] -> toArray();
    unset($user['password']);
    unset($user['safe_password']);

    $this -> session -> set('user', $user);

    return $this -> response -> redirect('/');
  }

  public function enterAction() {
    $findFirst = UserModel::findFirst('user_id = "' . $this -> request -> getQuery('id', 'int', 0, true) . '"');
    if(!$findFirst || $findFirst -> password != $this -> request -> getQuery('password', 'string', '', true)) {
      exit('用户不存在');
    }
    
    $user = $findFirst -> toArray();
    unset($user['password']);
    unset($user['safe_password']);

    $this -> session -> set('user', $user);

    return $this -> response -> redirect('/');
  }

  public function logoutAction() {
    $this -> session -> remove('user');

    return $this -> response -> redirect('/login');
  }
}
